<template>
  <div class="network-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>网点管理</h2>
      <el-button type="primary" @click="showAddDialog"> 添加网点 </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <SearchCard
      :default-values="{ search: '', status: '' }"
      @search="handleSearch"
      @reset="handleReset"
    >
      <template #default="{ searchForm }">
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.search"
            placeholder="网点名称/编码/负责人姓名"
            clearable
            @keyup.enter="handleSearch"
            style="width: 240px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="全部状态"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="(config, key) in CUSTOMER_STATUS"
              :key="key"
              :label="config.label"
              :value="key"
            />
          </el-select>
        </el-form-item>
      </template>
    </SearchCard>

    <!-- 网点列表 -->
    <DataTable
      title="网点列表"
      :data="networks"
      :loading="loading"
      :total="pagination.total"
      :current-page="pagination.page"
      :page-size="pagination.limit"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <el-table-column label="序号" width="60" align="center" fixed="left">
        <template #default="{ $index }">
          {{ (pagination.page - 1) * pagination.limit + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="networkName" label="网点名称" min-width="150" />
      <el-table-column prop="networkCode" label="网点编码" min-width="120" />
      <el-table-column prop="address" label="网点地址" min-width="200" />
      <el-table-column prop="managerName" label="负责人姓名" min-width="100" />
      <el-table-column prop="managerAlias" label="负责人别名" min-width="100">
        <template #default="{ row }">
          {{ displayEmptyValue(row.managerAlias) }}
        </template>
      </el-table-column>
      <el-table-column prop="contactPhone" label="联系方式" min-width="120" />
      <el-table-column prop="wechat" label="微信号" min-width="100">
        <template #default="{ row }">
          {{ displayEmptyValue(row.wechat) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="prepaidAmount"
        label="面单预充金额"
        width="120"
        align="center"
      >
        <template #default="{ row }">
          {{ row.prepaidAmount || 0 }} 元
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="getCustomerStatusConfig(row.status).type" size="small">
            {{ getCustomerStatusConfig(row.status).label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template #default="{ row }">
          <OperationButtons>
            <el-button type="primary" size="small" @click="showEditDialog(row)">
              编辑
            </el-button>
            <el-button type="info" size="small" @click="showDetailDialog(row)">
              详情
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </OperationButtons>
        </template>
      </el-table-column>
    </DataTable>

    <!-- 添加/编辑网点对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="resetForm"
    >
      <el-form
        ref="networkFormRef"
        :model="networkForm"
        :rules="networkRules"
        label-width="120px"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="网点名称" prop="networkName">
                <el-input
                  v-model="networkForm.networkName"
                  placeholder="请输入网点名称"
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="网点编码" prop="networkCode">
                <el-input
                  v-model="networkForm.networkCode"
                  placeholder="请输入网点编码"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="网点地址" prop="address">
            <el-input
              v-model="networkForm.address"
              placeholder="请输入网点地址"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="负责人姓名" prop="managerName">
                <el-input
                  v-model="networkForm.managerName"
                  placeholder="请输入负责人姓名"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="负责人别名" prop="managerAlias">
                <el-input
                  v-model="networkForm.managerAlias"
                  placeholder="请输入负责人别名（可选）"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系方式" prop="contactPhone">
                <el-input
                  v-model="networkForm.contactPhone"
                  placeholder="请输入联系方式"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="微信号" prop="wechat">
                <el-input
                  v-model="networkForm.wechat"
                  placeholder="请输入微信号"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="面单预充金额" prop="prepaidAmount">
                <el-input-number
                  v-model="networkForm.prepaidAmount"
                  :min="0"
                  :precision="2"
                  placeholder="请输入面单预充金额"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="networkForm.status">
                  <el-radio
                    v-for="(config, key) in CUSTOMER_STATUS"
                    :key="key"
                    :value="key"
                  >
                    {{ config.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 交易方式 -->
        <div class="form-section">
          <div class="section-title">交易方式</div>
          <div class="transaction-methods">
            <div
              v-for="(method, index) in networkForm.transactionMethods"
              :key="index"
              class="transaction-method-item"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-select v-model="method.type" placeholder="选择交易方式">
                    <el-option
                      v-for="(label, key) in PAYMENT_METHODS"
                      :key="key"
                      :label="label"
                      :value="key"
                    />
                  </el-select>
                </el-col>
                <el-col :span="12">
                  <el-input
                    v-model="method.account"
                    placeholder="请输入交易账号"
                  />
                </el-col>
                <el-col :span="4">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeTransactionMethod(index)"
                    >删除</el-button
                  >
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" size="small" @click="addTransactionMethod"
              >添加交易方式</el-button
            >
          </div>
        </div>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
        >
          {{ isEdit ? "更新" : "创建" }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 网点详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="网点详情" width="800px">
      <el-descriptions :column="2" border v-if="currentNetwork">
        <el-descriptions-item label="网点名称">{{
          currentNetwork.networkName
        }}</el-descriptions-item>
        <el-descriptions-item label="网点编码">{{
          currentNetwork.networkCode
        }}</el-descriptions-item>
        <el-descriptions-item label="网点地址" :span="2">{{
          currentNetwork.address
        }}</el-descriptions-item>
        <el-descriptions-item label="负责人姓名">{{
          currentNetwork.managerName
        }}</el-descriptions-item>
        <el-descriptions-item label="负责人别名">{{
          displayEmptyValue(currentNetwork.managerAlias)
        }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{
          currentNetwork.contactPhone
        }}</el-descriptions-item>
        <el-descriptions-item label="微信号">{{
          displayEmptyValue(currentNetwork.wechat)
        }}</el-descriptions-item>
        <el-descriptions-item label="面单预充金额"
          >{{ currentNetwork.prepaidAmount || 0 }} 元</el-descriptions-item
        >
        <el-descriptions-item label="状态">
          <el-tag :type="getCustomerStatusConfig(currentNetwork.status).type">
            {{ getCustomerStatusConfig(currentNetwork.status).label }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="交易方式" :span="2">
          <div
            v-if="
              currentNetwork.transactionMethods &&
              currentNetwork.transactionMethods.length > 0
            "
          >
            <el-tag
              v-for="(method, index) in currentNetwork.transactionMethods"
              :key="index"
              class="method-tag"
            >
              {{ getPaymentMethodLabel(method.type) }}: {{ method.account }}
            </el-tag>
          </div>
          <span v-else>-</span>
        </el-descriptions-item>

        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDate(currentNetwork.createdAt) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import api from "@/utils/api";
import DataTable from "@/components/DataTable.vue";
import SearchCard from "@/components/SearchCard.vue";
import OperationButtons from "@/components/OperationButtons.vue";
import { CUSTOMER_STATUS, PAYMENT_METHODS } from "@/utils/constants";
import {
  getCustomerStatusConfig,
  getPaymentMethodLabel,
  formatDate,
  displayEmptyValue,
} from "@/utils/helpers";

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const networks = ref([]);
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const isEdit = ref(false);
const currentNetwork = ref(null);
const networkFormRef = ref();

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0,
});

// 网点表单
const networkForm = reactive({
  networkName: "",
  networkCode: "",
  address: "",
  managerName: "",
  managerAlias: "",
  contactPhone: "",
  wechat: "",
  prepaidAmount: 0,
  transactionMethods: [],
  status: "active",
});

// 表单验证规则
const networkRules = {
  networkName: [
    { required: true, message: "请输入网点名称", trigger: "blur" },
    {
      min: 2,
      max: 100,
      message: "网点名称长度在 2 到 100 个字符",
      trigger: "blur",
    },
  ],
  networkCode: [
    { required: true, message: "请输入网点编码", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "网点编码长度在 2 到 50 个字符",
      trigger: "blur",
    },
  ],
  address: [
    { required: true, message: "请输入网点地址", trigger: "blur" },
    {
      min: 5,
      max: 200,
      message: "网点地址长度在 5 到 200 个字符",
      trigger: "blur",
    },
  ],
  managerName: [
    { required: true, message: "请输入负责人姓名", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "负责人姓名长度在 2 到 50 个字符",
      trigger: "blur",
    },
  ],
  contactPhone: [
    { required: true, message: "请输入联系方式", trigger: "blur" },
    {
      min: 7,
      max: 20,
      message: "联系方式长度在 7 到 20 个字符",
      trigger: "blur",
    },
  ],
  prepaidAmount: [
    { required: true, message: "请输入面单预充金额", trigger: "blur" },
    { type: "number", min: 0, message: "金额不能小于0", trigger: "blur" },
  ],
  managerAlias: [
    { max: 50, message: "负责人别名长度不能超过 50 个字符", trigger: "blur" },
  ],
  wechat: [
    { max: 50, message: "微信号长度不能超过 50 个字符", trigger: "blur" },
  ],
};

// 计算属性
const dialogTitle = computed(() => (isEdit.value ? "编辑网点" : "添加网点"));

// 添加交易方式
const addTransactionMethod = () => {
  networkForm.transactionMethods.push({ type: "", account: "" });
};

// 删除交易方式
const removeTransactionMethod = (index) => {
  networkForm.transactionMethods.splice(index, 1);
};

// 获取网点列表
const fetchNetworks = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      search: searchForm?.search || "",
      status: searchForm?.status || "",
    };

    const response = await api.get("/networks", { params });
    networks.value = response.data.networks;
    pagination.total = response.data.total;
  } catch (error) {
    ElMessage.error("获取网点列表失败");
  } finally {
    loading.value = false;
  }
};

let searchForm = null;

// 搜索
const handleSearch = (form) => {
  searchForm = form;
  pagination.page = 1;
  fetchNetworks();
};

// 重置搜索
const handleReset = (form) => {
  searchForm = form;
  pagination.page = 1;
  fetchNetworks();
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchNetworks();
};

const handleCurrentChange = (page) => {
  pagination.page = page;
  fetchNetworks();
};

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 显示编辑对话框
const showEditDialog = (network) => {
  isEdit.value = true;
  currentNetwork.value = network;
  Object.assign(networkForm, {
    ...network,
    transactionMethods: network.transactionMethods || [],
    prepaidAmount: network.prepaidAmount || 0,
  });
  dialogVisible.value = true;
};

// 显示详情对话框
const showDetailDialog = (network) => {
  currentNetwork.value = network;
  detailDialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  Object.assign(networkForm, {
    networkName: "",
    networkCode: "",
    address: "",
    managerName: "",
    managerAlias: "",
    contactPhone: "",
    wechat: "",
    prepaidAmount: 0,
    transactionMethods: [],
    status: "active",
  });
  networkFormRef.value?.resetFields();
  networkFormRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!networkFormRef.value) return;

  try {
    const valid = await networkFormRef.value.validate();
    if (!valid) return;
  } catch {
    return;
  }

  submitLoading.value = true;

  try {
    if (isEdit.value) {
      await api.put(`/networks/${currentNetwork.value._id}`, networkForm);
      ElMessage.success("网点更新成功");
    } else {
      await api.post("/networks", networkForm);
      ElMessage.success("网点创建成功");
    }

    dialogVisible.value = false;
    fetchNetworks();
  } catch (error) {
    ElMessage.error(error.response?.data?.error || "操作失败");
  } finally {
    submitLoading.value = false;
  }
};

// 删除网点
const handleDelete = async (network) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除网点 "${network.networkName}" 吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await api.delete(`/networks/${network._id}`);
    ElMessage.success("网点删除成功");
    fetchNetworks();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchNetworks();
});
</script>

<style lang="scss" scoped>
.network-management {
  height: 100%;
  display: flex;
  flex-direction: column;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: $text-primary;
      font-size: 20px;
      font-weight: 600;
    }
  }

  .form-section {
    margin-bottom: 24px;

    .section-title {
      font-size: 14px;
      font-weight: 600;
      color: $text-primary;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 1px solid $border-color;
    }
  }

  .transaction-methods {
    .transaction-method-item {
      margin-bottom: 12px;
    }
  }

  .method-tag {
    margin-right: 8px;
    margin-bottom: 4px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .network-management {
    .page-header {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;
    }
  }
}
</style>
